package com.z.audio;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
import static android.widget.Toast.LENGTH_SHORT;

public class AudioWidget extends AppWidgetProvider {
    private static final String TAG = "AudioWidget";

    public static final String ACTION_SPEAKER_PHONE_ON = "android.audio.ACTION_SPEAKER_PHONE_ON";
    public static final String ACTION_BLUETOOTH_SCO_ON = "android.audio.ACTION_BLUETOOTH_SCO_ON";

    public static final String TAG_WIDGET_ID = "APP_WIDGET_ID";
    private static final int DELAY_MILLIS = 200;

    @Override
    public void onReceive(final Context context, Intent intent) {
        super.onReceive(context, intent);

        String action = intent.getAction();

        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(TAG_WIDGET_ID)) {
            final int appWidgetId = intent.getIntExtra(TAG_WIDGET_ID, 0);
            if (ACTION_SPEAKER_PHONE_ON.equals(action)) {
                changeToSpeaker(appWidgetId);

                updateAppWidget(context, App.Widget, appWidgetId, true);
                App.Loople.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        updateAppWidget(context, App.Widget, appWidgetId, false);
                    }
                }, DELAY_MILLIS);

                Toast.makeText(App.Ctx, R.string.msg_on_speaker, LENGTH_SHORT).show();

            } else if (ACTION_BLUETOOTH_SCO_ON.equals(action)) {
                changeToBluetooth(appWidgetId);

                updateAppWidget(context, App.Widget, appWidgetId, true);
                App.Loople.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        updateAppWidget(context, App.Widget, appWidgetId, false);
                    }
                }, DELAY_MILLIS);

                Toast.makeText(App.Ctx, R.string.msg_on_bluetooth, LENGTH_SHORT).show();
            }
        }

        Log.d(TAG, ":: " + action);
    }

    /**
     * 切换到外放
     */
    public void changeToSpeaker(int appWidgetId) {
        //注意此处，蓝牙未断开时使用MODE_IN_COMMUNICATION而不是MODE_NORMAL
        App.Audio.setMode(AudioManager.MODE_NORMAL);
        App.Audio.stopBluetoothSco();
        App.Audio.setBluetoothScoOn(false);
        App.Audio.setSpeakerphoneOn(true);
    }

    /**
     * 切换到蓝牙音箱
     */
    public void changeToBluetooth(int appWidgetId) {
        App.Audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
        App.Audio.startBluetoothSco();
        App.Audio.setBluetoothScoOn(true);
        App.Audio.setSpeakerphoneOn(false);
    }

    /**
     * 切换到耳机模式
     */
    public void changeToHeadset(int appWidgetId) {
        App.Audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
        App.Audio.stopBluetoothSco();
        App.Audio.setBluetoothScoOn(false);
        App.Audio.setSpeakerphoneOn(false);

        Toast.makeText(App.Ctx, R.string.msg_on_headset, LENGTH_SHORT).show();
    }

    /**
     * 切换到听筒
     */
    public void changeToReceiver(int appWidgetId) {
        App.Audio.setSpeakerphoneOn(false);
        App.Audio.setMode(AudioManager.MODE_IN_CALL);

        Toast.makeText(App.Ctx, R.string.msg_on_phone, LENGTH_SHORT).show();
    }

    private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, boolean status) {

        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.audio_widget);
        views.setImageViewResource(R.id.image, status ? R.drawable.ic_audio_selected : R.drawable.ic_audio_normal);
        views.setTextViewText(R.id.label, context.getText(R.string.widget_label));


        Intent intent = new Intent(ACTION_SPEAKER_PHONE_ON);
        intent.setPackage(context.getPackageName());
        intent.putExtra(TAG_WIDGET_ID, appWidgetId);
        PendingIntent pi = PendingIntent.getBroadcast(context, appWidgetId, intent, FLAG_UPDATE_CURRENT);

        views.setOnClickPendingIntent(R.id.shell_panel, pi);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

        Log.d(TAG, String.format(":: updateAppWidget: %d", appWidgetId));
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId, false);
        }
    }

    @Override
    public void onEnabled(Context context) {

    }

    @Override
    public void onDisabled(Context context) {

    }
}

